package com.mashiguang.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.mashiguang.dao.UserDao;
import com.mashiguang.po.Authority;
import com.mashiguang.po.Group;
import com.mashiguang.po.Resource;
import com.mashiguang.po.User;
import com.mashiguang.vo.UserVo;

public class MyUserDetailService implements UserDetailsService {
	
	private UserDao userDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		
		User u = userDao.getUserByUsername(username);
		
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		
		List<Group> groups = u.getGroups();
		for (Group group : groups) {
			List<Authority> authorities = group.getAuthorities();
			for (final Authority authority : authorities) {
				/*List<Resource> resources = authority.getResources();
				for (final Resource resource : resources) {
					grantedAuthorities.add(new GrantedAuthority() {
						public String getAuthority() {
							return resource.getResourceUrl();
						}
					});
				}*/
				
				grantedAuthorities.add(new GrantedAuthority() {
					public String getAuthority() {
						return authority.getAuthority();
					}
				});
			}
		}
		
		return new UserVo(username, u.getPassword(), grantedAuthorities);
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

}
